Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

Code Examples

The first part of this tutorial used code fragments to walk you through the fundamentals of using the SAAJ API. In this section, you will use some of those code fragments to create applications. First, you will see the program Request.java. Then you will see how to run the programs MyUddiPing.java, HeaderExample.java, SOAPFaultTest.java, and DOMExample.java.

You do not have to start the J2EE Application Server in order to run these examples.

Request.java

The class Request.java puts together the code fragments used in Tutorial and adds what is needed to make it a complete example of a client sending a request-response message. In addition to putting all the code together, it adds import statements, a main method, and a try/catch block with exception handling.

import javax.xml.soap.*;
import java.util.*;
import java.net.URL;

public class Request {
    public static void main(String[] args)  {
        try {
            SOAPConnectionFactory soapConnectionFactory =
                SOAPConnectionFactory.newInstance();
            SOAPConnection connection =
                soapConnectionFactory.createConnection();
            SOAPFactory soapFactory = 
                SOAPFactory.newInstance();

            MessageFactory factory =
                MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            SOAPHeader header = message.getSOAPHeader();
            SOAPBody body = message.getSOAPBody();
            header.detachNode();

            Name bodyName = soapFactory.createName(
                "GetLastTradePrice", "m",
                "http://wombats.ztrade.com");
            SOAPBodyElement bodyElement =
                body.addBodyElement(bodyName);

            Name name = soapFactory.createName("symbol");
            SOAPElement symbol = 
                bodyElement.addChildElement(name);
            symbol.addTextNode("SUNW");

            URL endpoint = new URL
                ("http://wombat.ztrade.com/quotes");
            SOAPMessage response = 
                connection.call(message, endpoint);

            connection.close();

            SOAPBody soapBody = response.getSOAPBody();

            Iterator iterator = 
                soapBody.getChildElements(bodyName);
            SOAPBodyElement bodyElement =
                (SOAPBodyElement)iterator.next();
            String lastPrice = bodyElement.getValue();

            System.out.print("The last price for SUNW is ");
            System.out.println(lastPrice);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
} 

In order for Request.java to be runnable, the second argument supplied to the method call would have to be a valid existing URI, which is not true in this case. However, the application in the next section is one that you can run.

MyUddiPing.java

The program MyUddiPing.java is another example of a SAAJ client application. It sends a request to a Universal Description, Discovery and Integration (UDDI) service and gets back the response. A UDDI service is a business registry and repository from which you can get information about businesses that have registered themselves with the registry service. For this example, the MyUddiPing application is not actually accessing a UDDI service registry but rather a test (demo) version. Because of this, the number of businesses you can get information about is limited. Nevertheless, MyUddiPing demonstrates a request being sent and a response being received.

Setting Up

The myuddiping example is in the following directory:

<INSTALL>/j2eetutorial14/examples/saaj/myuddiping/ 

Note: <INSTALL> is the directory where you installed the J2EE Tutorial bundle.


In the myuddiping directory, you will find two files and the src directory. The src directory contains one source file, MyUddiPing.java.

The file uddi.properties contains the URL of the destination (the UDDI test registry) and the proxy host and proxy port of the sender. Edit this file to supply the correct proxy host and proxy port if you access the Internet from behind a firewall. If you are not sure what the values for these are, consult your system administrator or another person with that information.

The file build.xml is the build file for this example. It includes the file <INSTALL>/j2eetutorial14/examples/saaj/common/targets.xml, which contains a set of targets common to all the SAAJ examples.

The prepare target creates a directory named build. To invoke the prepare target, you type the following at the command line:

asant prepare 

The target named build compiles the source file MyUddiPing.java and puts the resulting .class file in the build directory. So to do these tasks, you type the following at the command line:

asant build 

Examining MyUddiPing

We will go through the file MyUddiPing.java a few lines at a time, concentrating on the last section. This is the part of the application that accesses only the content you want from the XML message returned by the UDDI registry.

The first few lines of code import the packages used in the application.

import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*; 

The next few lines begin the definition of the class MyUddiPing, which starts with the definition of its main method. The first thing it does is check to see if two arguments were supplied. If not, it prints a usage message and exits. The usage message mentions only one argument; the other is supplied by the build.xml target.

public class MyUddiPing {
    public static void main(String[] args) {
        try {
            if (args.length != 2) {
                System.err.println("Argument required: " +
                    "-Dbusiness-name=<name>");
                System.exit(1);
            } 

The following lines create a java.util.Properties object that contains the system properties and the properties from the file uddi.properties that is in the myuddiping directory.

            Properties myprops = new Properties();
            myprops.load(new FileInputStream(args[0]));

            Properties props = System.getProperties();

            Enumeration enum = myprops.propertyNames();
            while (enum.hasMoreElements()) {
                String s = (String)enum.nextElement(); 
                props.put(s, myprops.getProperty(s));
            } 

The next four lines create a SOAPMessage object. First, the code gets an instance of SOAPConnectionFactory and uses it to create a connection. Then it gets an instance of MessageFactory and uses it to create a message.

            SOAPConnectionFactory soapConnectionFactory =
                SOAPConnectionFactory.newInstance();
            SOAPConnection connection =
                soapConnectionFactory.createConnection();
            MessageFactory messageFactory =
                MessageFactory.newInstance();

            SOAPMessage message = 
                messageFactory.createMessage(); 

The next lines of code retrieve the SOAPHeader and SOAPBody objects from the message and remove the header.

           SOAPHeader header = message.getSOAPHeader();
           SOAPBody body = message.getSOAPBody();
            header.detachNode(); 

The following lines of code create the UDDI find_business message. The first line gets a SOAPFactory instance that we will use to create names. The next line adds the SOAPBodyElement with a fully qualified name, including the required namespace for a UDDI version 2 message. The next lines add two attributes to the new element: the required attribute generic, with the UDDI version number 2.0, and the optional attribute maxRows, with the value 100. Then the code adds a child element with the Name object name and adds text to the element with the method addTextNode. The text added is the business name you will supply at the command line when you run the application.

            SOAPFactory soapFactory = 
                SOAPFactory.newInstance();
            SOAPBodyElement findBusiness = 
                body.addBodyElement(soapFactory.createName(
                    "find_business", "", 
                    "urn:uddi-org:api_v2"));
            findBusiness.addAttribute(soapFactory.createName(
                "generic"), "2.0");
            findBusiness.addAttribute(soapFactory.createName(
                "maxRows"), "100");
            SOAPElement businessName = 
                findBusiness.addChildElement(
                    soapFactory.createName("name"));
            businessName.addTextNode(args[1]); 

The next line of code saves the changes that have been made to the message. This method will be called automatically when the message is sent, but it does not hurt to call it explicitly.

            message.saveChanges(); 

The following lines display the message that will be sent:

            System.out.println("\n--- Request Message ---\n");
            message.writeTo(System.out); 

The next line of code creates the java.net.URL object that represents the destination for this message. It gets the value of the property named URL from the system property file.

            URL endpoint = new URL(
                System.getProperties().getProperty("URL")); 

Next the message message is sent to the destination that endpoint represents, which is the UDDI test registry. The call method will block until it gets a SOAPMessage object back, at which point it returns the reply.

            SOAPMessage reply = 
                connection.call(message, endpoint); 

In the next lines of code, the first line prints out a line giving the URL of the sender (the test registry), and the others display the returned message.

            System.out.println("\n\nReceived reply from: " + 
                endpoint);
            System.out.println("\n---- Reply Message ----\n");
            reply.writeTo(System.out); 

The returned message is the complete SOAP message, an XML document, as it looks when it comes over the wire. It is a businessList that follows the format specified in http://uddi.org/pubs/DataStructure-V2.03-Published-20020719.htm#_Toc25130802.

As interesting as it is to see the XML that is actually transmitted, the XML document format does not make it easy to see the text that is the message's content. To remedy this, the last part of MyUddiPing.java contains code that prints out just the text content of the response, making it much easier to see the information you want.

Because the content is in the SOAPBody object, the first thing you need to do is access it, as shown in the following line of code.

            SOAPBody replyBody = reply.getSOAPBody(); 

Next the code displays a message describing the content:

            System.out.println("\n\nContent extracted from " +
                "the reply message:\n"); 

To display the content of the message, the code uses the known format of the reply message. First it gets all the reply body's child elements named businessList:

            Iterator businessListIterator =
                replyBody.getChildElements(
                    soapFactory.createName("businessList", 
                        "", "urn:uddi-org:api_v2")); 

The method getChildElements returns the elements in the form of a java.util.Iterator object. You access the child elements by calling the method next on the Iterator object.

An immediate child of a SOAPBody object is a SOAPBodyElement object.

We know that the reply can contain only one businessList element, so the code then retrieves this one element by calling the iterator's next method. Note that the method Iterator.next returns an Object, which has to be cast to the specific kind of object you are retrieving. Thus, the result of calling businessListIterator.next is cast to a SOAPBodyElement object:

            SOAPBodyElement businessList = 
                (SOAPBodyElement)businessListIterator.next(); 

The next element in the hierarchy is a single businessInfos element, so the code retrieves this element the same way it retrieved the businessList. Children of SOAPBodyElement objects and all child elements from there down are SOAPElement objects.

            Iterator businessInfosIterator =
                businessList.getChildElements(
                    soapFactory.createName("businessInfos",
                        "", "urn:uddi-org:api_v2"));

            SOAPElement businessInfos = 
                (SOAPElement)businessInfosIterator.next(); 

The businessInfos element contains zero or more businessInfo elements. If the query returned no businesses, the code prints a message saying that none were found. If the query returned businesses, however, the code extracts the name and optional description by retrieving the child elements with those names. The method Iterator.hasNext can be used in a while loop because it returns true as long as the next call to the method next will return a child element. Accordingly, the loop ends when there are no more child elements to retrieve.

            Iterator businessInfoIterator =
                businessInfos.getChildElements(
                    soapFactory.createName("businessInfo", 
                        "", "urn:uddi-org:api_v2"));

            if (! businessInfoIterator.hasNext()) {
                System.out.println("No businesses found " +
                    "matching the name '" + args[1] + 
                    "'.");
            } else {
                while (businessInfoIterator.hasNext()) {
                    SOAPElement businessInfo = (SOAPElement)
                        businessInfoIterator.next();
                    // Extract name and description from the
                    // businessInfo
                    Iterator nameIterator = 
                        businessInfo.getChildElements(
                            soapFactory.createName("name",
                                "", "urn:uddi-org:api_v2"));
                    while (nameIterator.hasNext()) {
                        businessName = 
                            (SOAPElement)nameIterator.next();
                        System.out.println("Company name: " +
                            businessName.getValue());
                    }
                    Iterator descriptionIterator = 
                        businessInfo.getChildElements(
                            soapFactory.createName(
                                "description", "",
                                "urn:uddi-org:api_v2"));
                    while (descriptionIterator.hasNext()) {
                        SOAPElement businessDescription = 
                            (SOAPElement)
                            descriptionIterator.next();
                        System.out.println("Description: " +
                            businessDescription.getValue());
                    }
                    System.out.println("");
                } 

Running MyUddiPing

You compile MyUddiPing.java by typing the following at the command line:

cd <INSTALL>/j2eetutorial14/examples/saaj/myuddiping
asant build 

With the code compiled, you are ready to run MyUddiPing. The run target takes two arguments, but you need to supply only one of them. The first argument is the file uddi.properties, which is supplied by a property set in build.xml. The other argument is the name of the business for which you want to get a description, and you need to supply this argument on the command line. Note that any property set on the command line overrides any value set for that property in the build.xml file.

asant run -Dbusiness-name="food" 

Output similar to the following will appear after the full XML message:

Content extracted from the reply message:

Company name: Food
Description: Test Food

Company name: Food Manufacturing

Company name: foodCompanyA
Description: It is a food company sells biscuit 

If you want to run MyUddiPing again, you may want to start over by deleting the build directory and the .class file it contains. You can do this by typing the following at the command line:

asant clean 

HeaderExample.java

The example HeaderExample.java, based on the code fragments in the section Adding Attributes, creates a message with several headers. It then retrieves the contents of the headers and prints them out. You will find the code for HeaderExample in the following directory:

<INSTALL>/j2eetutorial14/examples/saaj/headers/src/ 

Running HeaderExample

To run HeaderExample, you use the file build.xml that is in the directory <INSTALL>/j2eetutorial14/examples/saaj/headers/.

To run HeaderExample, use the following command:

asant run 

This command executes the prepare, build, and run targets in the build.xml and targets.xml files.

When you run HeaderExample, you will see output similar to the following:

----- Request Message ----

<SOAP-ENV:Envelope 
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<ns:orderDesk SOAP-ENV:actor="http://gizmos.com/orders" 
xmlns:ns="http://gizmos.com/NSURI"/>
<ns:shippingDesk SOAP-ENV:actor="http://gizmos.com/shipping" 
xmlns:ns="http://gizmos.com/NSURI"/>
<ns:confirmationDesk 
SOAP-ENV:actor="http://gizmos.com/confirmations" 
xmlns:ns="http://gizmos.com/NSURI"/>
<ns:billingDesk SOAP-ENV:actor="http://gizmos.com/billing" 
xmlns:ns="http://gizmos.com/NSURI"/>
<t:Transaction SOAP-ENV:mustUnderstand="1" 
xmlns:t="http://gizmos.com/orders">5</t:Transaction>
</SOAP-ENV:Header><SOAP-ENV:Body/></SOAP-ENV:Envelope>
Header name is ns:orderDesk
Actor is http://gizmos.com/orders
MustUnderstand is false

Header name is ns:shippingDesk
Actor is http://gizmos.com/shipping
MustUnderstand is false

Header name is ns:confirmationDesk
Actor is http://gizmos.com/confirmations
MustUnderstand is false

Header name is ns:billingDesk
Actor is http://gizmos.com/billing
MustUnderstand is false

Header name is t:Transaction
Actor is null
MustUnderstand is true 

SOAPFaultTest.java

The example SOAPFaultTest.java, based on the code fragments in the sections Creating and Populating a SOAPFault Object and Retrieving Fault Information, creates a message with a SOAPFault object. It then retrieves the contents of the SOAPFault object and prints them out. You will find the code for SOAPFaultTest in the following directory:

<INSTALL>/j2eetutorial14/examples/saaj/fault/src/ 

Running SOAPFaultTest

To run SOAPFaultTest, you use the file build.xml that is in the directory <INSTALL>/j2eetutorial14/examples/saaj/fault/.

To run SOAPFaultTest, use the following command:

asant run 

When you run SOAPFaultTest, you will see output like the following (line breaks have been inserted in the message for readability):

Here is what the XML message looks like: 
<SOAP-ENV:Envelope 
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/><SOAP-ENV:Body>
<SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Message does not have necessary info</faultstring>
<faultactor>http://gizmos.com/order</faultactor>
<detail>
<PO:order xmlns:PO="http://gizmos.com/orders/">
Quantity element does not have a value</PO:order>
<PO:confirmation xmlns:PO="http://gizmos.com/confirm">
Incomplete address: no zip code</PO:confirmation>
</detail></SOAP-ENV:Fault>
</SOAP-ENV:Body></SOAP-ENV:Envelope>

SOAP fault contains: 
   Fault code = SOAP-ENV:Client
   Local name = Client
   Namespace prefix = SOAP-ENV, bound to 
http://schemas.xmlsoap.org/soap/envelope/
   Fault string = Message does not have necessary info
   Fault actor = http://gizmos.com/order
   Detail entry = Quantity element does not have a value
   Detail entry = Incomplete address: no zip code 

DOMExample.java

The example DOMExample.java shows how to add a DOM document to the body of a message and then to traverse its contents. You will find the code for DOMExample in the following directory:

<INSTALL>/j2eetutorial14/examples/saaj/dom/src/ 

This example first creates a DOM document by parsing an XML document, almost exactly like the JAXP example DomEcho01.java in the directory <INSTALL>/j2eetutorial14/examples/jaxp/dom/samples/. The file it parses is one that you specify on the command line.

static Document document;
...
    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = 
            factory.newDocumentBuilder();
        document = builder.parse( new File(args[0]) );
        ... 

Next, the example creates a SOAP message in the usual way. Then it adds the document to the message body:

        SOAPBodyElement docElement = 
            body.addDocument(document); 

This example does not change the content of the message. Instead, it displays the message content and then uses a recursive method, getContents, to traverse the element tree using SAAJ APIs and display the message contents in a readable form.

    public void getContents(Iterator iterator, 
        String indent) {

        while (iterator.hasNext()) {
            SOAPElement element = 
                (SOAPElement)iterator.next();
            Name name = element.getElementName();
            System.out.println(indent + "Name is " + 
                name.getQualifiedName());
            String content = element.getValue();
            if (content != null) {
                System.out.println(indent + "Content is " +
                    content);
            }
            Iterator attrs = element.getAllAttributes();
            while (attrs.hasNext()){
                Name attrName = (Name)attrs.next();
                System.out.println(indent + 
                    " Attribute name is " + 
                    attrName.getQualifiedName());
                System.out.println(indent + 
                    " Attribute value is " + 
                    element.getAttributeValue(attrName));
            }
            if (content == null) {
                Iterator iter2 = element.getChildElements();
                getContents(iter2, indent + " ");
            }
        }
    } 

Running DOMExample

To run DOMExample, you use the file build.xml that is in the directory <INSTALL>/j2eetutorial14/examples/saaj/dom/. This directory also contains several sample XML files you can use:

To run DOMExample, use a command like the following:

asant run -Dxml-file=FindBusiness.xml 

After running DOMExample, you will see output something like the following:

Running DOMExample.
Name is find_business
 Attribute name is generic
 Attribute value is 2.0
 Attribute name is xmlns
 Attribute value is urn:uddi-org:api_v2
 Name is name
 Content is: %Coff% 

Conclusion

SAAJ provides a Java API for writing and sending XML messages. You have seen how to use this API to write client code for SAAJ request-response messages. You have also seen how to get the content from a response message.

You now have first-hand experience of how SAAJ makes it easier to do XML messaging.

Divider
Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.